<template>
  <div class="tinymce-editor">
    <Editor
      :id="editorId"
      v-model="editorValue"
      :init="editorInit"
      @onClick="handleClick"
    />
  </div>
</template>

<script>
// 引入组件
import tinymce from "tinymce/tinymce";
import Editor from "@tinymce/tinymce-vue";
// 引入富文本编辑器主题的js和css
import "tinymce/themes/silver/theme.min.js";
import "tinymce/skins/ui/oxide/skin.min.css";

// 扩展插件
import 'tinymce/themes/silver/theme'
import 'tinymce/icons/default'

import "tinymce/plugins/code";
import "tinymce/plugins/autosave";
import "tinymce/plugins/preview";
import "tinymce/plugins/paste";
import "tinymce/plugins/searchreplace";
import "tinymce/plugins/fullscreen";
import "tinymce/plugins/media";
import "tinymce/plugins/codesample";
import "tinymce/plugins/pagebreak";
import "tinymce/plugins/anchor";
import "tinymce/plugins/toc";
import 'tinymce/plugins/image'
import 'tinymce/plugins/link'
import 'tinymce/plugins/table'
import 'tinymce/plugins/lists'

import 'tinymce/plugins/importword'
import 'tinymce/plugins/formatpainter'
import "tinymce/plugins/axupimgs";

import OSS from 'ali-oss'
import setting from '@/config/setting.js'
export default {
  name: "TinymceEditor",
  components: { Editor },
  props: {
    id: {
      type: String,
      default: "tinymceEditor",
    },
    value: {
      type: String,
      default: "",
    }
  },
  data() {
    var that = this;
    return {
      obj: '',
      editorInit: {
        language_url: "/tinymce/langs/zh_CN.js",
        language: "zh_CN",
        skin_url: "/tinymce/skins/ui/oxide",
        initialValue: '',//初始值
        statusbar: false, // 隐藏版权信息
        init_instance_callback: function(e){ // 版权信息
          var dom = document.getElementsByClassName('tox-statusbar')
          var domA = dom[0].getElementsByTagName('a')[0]
          if(domA){
            domA.innerText = '技术支持 新墨科技（使用字体时请注意字体版权）'
            domA.href = 'https://www.sinmore.com.cn/'
          }
        },
        height: '500px',
        width: '800px',
        menu: {
          file: {title: '文件', items: 'newdocument restoredraft | preview'},
          edit: {title: '编辑', items: 'undo redo | cut copy paste pastetext | selectall | searchreplace'},
          insert: {title: '插入', items: 'image link media codesample inserttable | pagebreak anchor toc'},
          view: {title: '查看', items: 'code | visualaid | preview fullscreen'},
          // format: {title: '格式', items: 'bold italic underline strikethrough superscript subscript codeformat | formats align fontselect | removeformat'},
          // table: {title: '表格', items: 'inserttable tableprops deletetable | cell row column'},
          // tools: {title: '工具', items: 'spellchecker code'}
        },
        plugins: 'table lists link preview code anchor autolink autosave directionality pagebreak paste toc fullscreen searchreplace media codesample image axupimgs formatpainter imagetools importword',
        toolbar: [
        'fontsizeselect bold italic strikethrough forecolor backcolor | alignleft aligncenter alignright alignjustify | indent outdent | numlist bullist',
        'link image axupimgs media importword | searchreplace anchor paste removeformat formatpainter | fullscreen'
        ],
        fontsize_formats: '12px 14px 16px 18px 24px 36px 48px 56px 72px',
        font_formats: '微软雅黑=Microsoft YaHei,Helvetica Neue,PingFang SC,sans-serif;苹果苹方=PingFang SC,Microsoft YaHei,sans-serif;宋体=simsun,serif;仿宋体=FangSong,serif;黑体=SimHei,sans-serif;Arial=arial,helvetica,sans-serif;Arial Black=arial black,avant garde;Book Antiqua=book antiqua,palatino;思源=Source Han Sans CN;',
        relative_urls: false,
        autosave_prefix: 'richText',//自动保存 localstorageKey
        autosave_retention: '300m',//草稿有效时间
        autosave_interval: '10s',//草稿保存时间
        axupimgs_filetype: '.png, .jpg, .jpeg, .gif',
        images_upload_handler: function(blobInfo, success, failure){
          //@todo 多图上传图片
          console.log('多图上传')
          var file = blobInfo.file ? blobInfo.file : blobInfo.blob();
          var size = setting.imageSize;
          if(file.size > size*1024*1024){
            return that.$message.error('请上传少于'+size+'M的图片')
          }
          var loading = that.$loading({
            lock: true,
            text: 'Loading',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          })
          var obj = that.getFileName(file);
          var res = that.obj;
          var client = new OSS({
            region: res.region_id,
            accessKeyId: res.Credentials.AccessKeyId,
            accessKeySecret: res.Credentials.AccessKeySecret,
            bucket: res.bucket,
            Expiration: res.Credentials.Expiration,
            stsToken: res.Credentials.SecurityToken
          })
          client.put("default/" + obj.timestamp + '/' + obj.file.name, obj.file).then(retult => {
            loading.close();
            if (retult.res.statusCode === 200) {
              var url = res.host + '/' + retult.name;
              success(url);
            }else {
              options.onError("上传失败")
            }
          })
        },
        // 导入word
        importword_handler: function(editor,files,next){
          // console.log(editor);
          // console.log(files[0].name);
          next(files);
        },
        importword_filter: function(result,insert,message){
          // console.log(message)
          // 自定义操作部分
          insert(result) //回插函数
        },
        // 文件上传
        file_picker_callback: function(callback, value, meta) {
          var filetype='.png, .jpg, .jpeg, .git';
          var input = document.createElement('input');
          var size = '';
          var msg = '';
          switch (meta.filetype) {
            case 'image':
              msg = '图片'
              size = setting.imageSize;
              filetype = '.jpg, .jpeg, .png, .gif';
              break;
            case 'media':
              msg = '视频'
              size = setting.videoSize;
              filetype = '.mp3, .mp4';
              break;
            case 'file':
            default:
          }
          input.setAttribute('type', 'file');
          input.setAttribute('accept', filetype);
          input.click();
          input.onchange = function(){
            var file = this.files[0];
            if(file.size > size*1024*1024){
              return that.$message.error('请上传少于'+size+'M的'+msg)
            }
            var loading = that.$loading({
              lock: true,
              text: 'Loading',
              spinner: 'el-icon-loading',
              background: 'rgba(0, 0, 0, 0.7)'
            })
            var obj = that.getFileName(file);
            var res = that.obj;
            var client = new OSS({
              region: res.region_id,
              accessKeyId: res.Credentials.AccessKeyId,
              accessKeySecret: res.Credentials.AccessKeySecret,
              bucket: res.bucket,
              Expiration: res.Credentials.Expiration,
              stsToken: res.Credentials.SecurityToken
            })
            client.put("default/" + obj.timestamp + '/' + obj.file.name, file).then(retult => {
              loading.close();
              if (retult.res.statusCode === 200) {
                var url = res.host + '/' + retult.name;
                callback(url, { title: file.name });
              }else {
                options.onError("上传失败")
              }
            })
          }
        },
      },
      editorId: this.id,
      editorValue: this.value,
    };
  },

  watch: {
    editorValue(newValue) {
      this.$emit("input", newValue);
    },
    value(newValue){
      this.editorInit.initialValue = newValue;
      this.editorValue = newValue;
      // console.log(this.editorInit.initialValue)
    }
  },

  mounted() {
    this.editorInit.initialValue = this.value;
    this.$api.get('common/asset/ststoken').then(res => {
      this.obj = res;
    })
    tinymce.init({});
  },

  methods: {
    // https://github.com/tinymce/tinymce-vue => All available events

    handleClick(e) {
      this.$emit("onClick", e, tinymce);
    },

    clear() {
      this.editorValue = "";
    },
  },
};
</script>